<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">

    
      <link rel="icon" href="/favicon.png" />
    

    <title>
        
          CODE&#39;NOTE
        
    </title>

    <!-- Spectre.css framework -->
    <link href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre.min.css" rel="stylesheet">
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-exp.min.css" rel="stylesheet">
    <link href="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-icons.min.css" rel="stylesheet">

    <!-- theme css & js -->
    
<link rel="stylesheet" href="/css/book.css">

    
<script src="/js/book.js"></script>


    <!-- tocbot -->
    <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.min.js"></script>
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.css" rel="stylesheet">
    
    <!-- katex -->    
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/KaTeX/0.15.2/katex.min.css" rel="stylesheet">

    
    
<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/zooming/2.1.1/zooming.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const zooming = new Zooming()
    zooming.listen('.book-content img')
})
</script>

<meta name="generator" content="Hexo 6.1.0"></head>

<body>

<div class="book-container">
  <div class="book-sidebar">
    <div class="book-brand">
  <a href="/">
    <img src="/favicon.png">
    <span>CODE&#39;NOTE</span>
  </a>
</div>
    <div id="menu" class="book-menu hide">
  <h2 id="☘️-Home">☘️ <a href="/">Home</a></h2>
<h2 id="Go">Go</h2>
<ul>
<li><a href="/go/01%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA">0.1 开发环境搭建</a></li>
<li><a href="/go/02%E5%8F%98%E9%87%8F%E5%92%8C%E5%B8%B8%E9%87%8F">0.2 变量和常量</a></li>
<li><a href="/go/03%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">0.3 基本数据类型</a></li>
<li><a href="/go/04%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E5%92%8C%E8%BF%90%E7%AE%97%E7%AC%A6">0.4 流程控制和运算符</a></li>
<li><a href="/go/05%E6%95%B0%E7%BB%84">0.5 数组</a></li>
<li><a href="/go/06%E5%88%87%E7%89%87">0.6 切片</a></li>
<li><a href="/go/07map">0.7 map</a></li>
<li><a href="/go/08%E5%87%BD%E6%95%B0">0.8 函数</a></li>
<li><a href="/go/09%E6%8C%87%E9%92%88">0.9 指针</a></li>
<li><a href="/go/10%E5%8F%8D%E5%B0%84">1.0 反射</a></li>
<li><a href="/go/11%E7%BB%93%E6%9E%84%E4%BD%93">1.1 结构体</a></li>
<li><a href="/go/12%E6%8E%A5%E5%8F%A3">1.2 接口</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/goroutine">1.3 goroutine</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/channel">1.4 channel</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%B9%B6%E5%8F%91%E5%AE%89%E5%85%A8%E5%92%8C%E9%94%81">1.5 并发安全和锁</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C">1.6 原子操作</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/GPM%E5%8E%9F%E7%90%86%E4%B8%8E%E8%B0%83%E5%BA%A6">1.7 GPM与调度分析</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/CSP%E5%B9%B6%E5%8F%91%E6%A8%A1%E5%9E%8B">1.8 CSP并发模型</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/fmt">标准库fmt</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/flag">标准库flag</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/time">标准库time</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/go_%E6%A0%87%E5%87%86%E5%BA%93log">标准库log</a></li>
</ul>
<!-- ##
## .NET

* [C# 入门基础合集](/dotnet/基础合集)
* [C# 面向对象](/dotnet/面向对象)
* [C# 数据结构](/dotnet/数据结构)
* [C# 泛型技术](/dotnet/泛型技术)
* [C# 反射技术](/dotnet/反射技术)
* [C# 多线程开发](/dotnet/多线程开发)
* [C# 多线程之线程同步技术](/dotnet/多线程之线程同步技术)
* [C# 委托和事件详解](/dotnet/委托和事件详解)
* [C# 并行编程](/dotnet/并行编程)
* [C# 异步编程](/dotnet/异步编程)
* [C# 值类型和引用类型内存分配](/dotnet/值类型和引用类型的内存分配)
* [1.1 DataProtection简介](/dotnet/1.1DataProtection简介)
* [1.2 DataProtection方法介绍](/dotnet/1.2DataProtection方法介绍)
* [1.3 落地实践及多环境调试](/dotnet/1.3落地实践及多环境调试)
* [1.4 UserSecrets](/dotnet/1.4UserSecrets)
* [1.5 数据保护方案](/dotnet/1.5基于DataProtection的数据保护方案)
* [1.6 集成AzureDevops](/dotnet/1.6方案实践及集成AzureDevops管道)


ELK Stack

* [ElastaticSearch入门](/elk/1.1ElastaticSearch入门)
* [ElastaticSearch配置](/elk/1.2ElastaticSearch配置)
* [使用Kibana操作ES](/elk/1.3使用Kibana操作ES)
 ## Docker

* [1.1 Docker概念及安装](/docker/1.1Docker概念及安装)
* [1.2 Docker镜像](/docker/1.2Docker镜像)
* [1.3 Docker容器](/docker/1.3Docker容器)
* [1.4 Docker仓库](/docker/1.4Docker仓库)
* [1.5 Docker数据管理](/docker/1.5Docker数据管理)
* [1.6 Docker容器四种网络模式](/docker/1.6Docker容器四种网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9Docker三剑客之DockerCompose)
* [2.0 DockerMachine](/docker/2.0Docker三剑客之DockerMachine)
* [2.1 DockerSwarm](/docker/2.1Docker三剑客之DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板)
* [1.6 Docker四种网络模式](/docker/1.6Docker容器网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9DockerCompose)
* [2.0 DockerMachine](/docker/2.0DockerMachine)
* [2.1 DockerSwarm](/docker/2.1DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板) 

## Linux

* [Centos安装](/linux/Centos安装)
* [Linux目录说明](/linux/Linux目录说明)
* [Centos网络配置](/linux/Centos网络配置)
* [Centos7升级gcc版本](/linux/Centos7升级gcc版本)
* [Linux常用命令](/linux/Linux常用命令)

## RabbitMQ

* [1.1 RabbitMQ概念及安装](/rabbitMq/1.1RabbitMQ概念及安装)
* [1.2 工作模式介绍](/rabbitMq/1.2工作模式介绍)
* [1.3 消息确认及持久化](/rabbitMq/1.3消息确认及持久化)
* [1.4 两种消费模式和QOS](/rabbitMq/1.4两种消费模式和QOS的实现)
* [1.5 Channel常见方法](/rabbitMq/1.5Channel常见方法)
* [1.6 RabbitMQ常用命令](/rabbitMq/1.6RabbitMQ常用命令)
* [1.7 RabbitMQ常见策略](/rabbitMq/1.7RabbitMQ常见策略)
* [1.8 RabbitMQ常见问题](/rabbitMq/1.8RabbitMQ常见问题)
* [1.9 RabbitMQ集群方案](/rabbitMq/1.9RabbitMQ集群方案)
* [客户端连接RabbitMQ](/rabbitMq/客户端连接RabbitMQ)

## Redis

* [1.1 NoSql概述](/redis/1.1NoSql概述)
* [1.2 Redis安装](/redis/1.2Redis安装)
* [1.3 Redis基本数据类型](/redis/1.3Redis基本数据类型)
* [1.4 Redis特殊数据类型](/redis/1.4Redis特殊数据类型)
* [1.5 Redis事务操作](/redis/1.5Redis事务操作)
* [1.6 Redis配置文件详解](/redis/1.6Redis配置文件详解)
* [1.7 Redis持久化](/redis/1.7Redis持久化)
* [1.8 Redis发布订阅](/redis/1.8Redis发布订阅)
* [1.9 Redis集群方案](/redis/1.9Redis集群方案)
* [1.10 Redis常见问题](/redis/1.10Redis常见问题)
* [客户端连接Redis](/redis/客户端连接Redis)
* [使用Docker搭建Redis集群](/redis/使用Docker搭建Redis集群)

## MicroService

* [1.1 微服务之项目搭建](/microservice/1.1微服务入门之项目搭建)
* [1.2 微服务之服务注册发现](/microservice/1.2微服务入门之服务注册与发现)
* [1.3 微服务之网关](/microservice/1.3微服务入门之网关)
* [1.4 微服务之事件总线](/microservice/1.4微服务入门之事件总线)
* [1.5 微服务之DockerCompose](/microservice/1.5微服务入门之DockerCompose)
* [Consul服务注册发现](/microservice/Consul服务注册发现)

## Test

* [单元测试](/test/单元测试)
* [集成测试](/test/集成测试)
* [压力测试k6](/test/压力测试k6)
* [自动化UI测试](/test/自动化UI测试) -->

</div>


<script src="/js/book-menu.js"></script>

  </div>

  <div class="sidebar-toggle" onclick="sidebar_toggle()" onmouseover="add_inner()" onmouseleave="remove_inner()">
  <div class="sidebar-toggle-inner"></div>
</div>

<script>
function add_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.add('show')  
}

function remove_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.remove('show')
}

function sidebar_toggle() {
    let sidebar_toggle = document.querySelector('.sidebar-toggle')
    let sidebar = document.querySelector('.book-sidebar')
    let content = document.querySelector('.off-canvas-content')
    if (sidebar_toggle.classList.contains('extend')) { // show
        sidebar_toggle.classList.remove('extend')
        sidebar.classList.remove('hide')
        content.classList.remove('extend')
    }
    else { // hide
        sidebar_toggle.classList.add('extend')
        sidebar.classList.add('hide')
        content.classList.add('extend')
    }
}
</script>

  <div class="off-canvas-content">
    <div class="columns">
      <div class="column col-10 col-lg-12">
        <div class="book-navbar">
          <!-- For Responsive Layout -->

<header class="navbar">
  <section class="navbar-section">
    <a onclick="open_sidebar()">
      <i class="icon icon-menu"></i>
    </a>
  </section>
</header>

        </div>
        <div class="book-content">
          <div class="book-post">
  <p>学习Go语言内置的 <code>time</code> 包的基本用法，<code>time</code> 包提供了时间的显示和计算用的函数。日历计算采用公历。</p>
<p>时间可分为时间点与时间段，Go 提供了以下两种基础类型</p>
<ul>
<li>时间点 <code>Time</code></li>
<li>时间段 <code>Duration</code></li>
</ul>
<p>除此之外也提供了以下类型，做一些特定的业务</p>
<ul>
<li>时区 <code>Location</code></li>
<li><code>Ticker</code></li>
<li>定时器 <code>Timer</code></li>
</ul>
<h1 id="时间点">时间点</h1>
<p>一般使用的所有与时间相关的业务都是基于点而延伸的，两点组成一个时间段，大多数应用也都是围绕这些点与面去做逻辑处理。</p>
<h2 id="初始化">初始化</h2>
<p>go 针对不同的参数类型提供了以下初始化的方式</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// func Now() Time</span></span><br><span class="line">fmt.Println(time.Now())</span><br><span class="line"></span><br><span class="line"><span class="comment">// func Parse(layout, value string) (Time, error)</span></span><br><span class="line">time.Parse(<span class="string">&quot;2016-01-02 15:04:05&quot;</span>, <span class="string">&quot;2018-04-23 12:24:51&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// func ParseInLocation(layout, value string, loc *Location) (Time, error) (layout已带时区时可直接用Parse)</span></span><br><span class="line">time.ParseInLocation(<span class="string">&quot;2006-01-02 15:04:05&quot;</span>, <span class="string">&quot;2017-05-11 14:06:06&quot;</span>, time.Local)</span><br><span class="line"></span><br><span class="line"><span class="comment">// func Unix(sec int64, nsec int64) Time</span></span><br><span class="line">time.Unix(<span class="number">1e9</span>, <span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time</span></span><br><span class="line">time.Date(<span class="number">2018</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">15</span>, <span class="number">30</span>, <span class="number">10</span>, <span class="number">0</span>, time.Local)</span><br><span class="line"></span><br><span class="line"><span class="comment">// func (t Time) In(loc *Location) Time 当前时间对应指定时区的时间</span></span><br><span class="line">loc, _ := time.LoadLocation(<span class="string">&quot;America/Los_Angeles&quot;</span>)</span><br><span class="line">fmt.Println(time.Now().In(loc))</span><br><span class="line"></span><br><span class="line"><span class="comment">// func (t Time) Local() Time</span></span><br></pre></td></tr></table></figure>
<p>获取到时间点之后为了满足业务和设计，需要转换成需要的格式，也就是所谓的时间格式化。</p>
<h2 id="格式化">格式化</h2>
<h3 id="to-string">to string</h3>
<p>格式化为字符串我们需要使用 time.Format 方法来转换成我们想要的格式</p>
<pre><code>  fmt.Println(time.Now().Format(&quot;2006-01-02 15:04:05&quot;))  // 2018-04-24 10:11:20
  fmt.Println(time.Now().Format(time.UnixDate))         // Tue Apr 24 09:59:02 CST 2018
</code></pre>
<p>Format 函数中可以指定你想使用的格式，同时 time 包中也给了一些我们常用的格式</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">const (</span><br><span class="line">    ANSIC       = &quot;Mon Jan _2 15:04:05 2006&quot;</span><br><span class="line">    UnixDate    = &quot;Mon Jan _2 15:04:05 MST 2006&quot;</span><br><span class="line">    RubyDate    = &quot;Mon Jan 02 15:04:05 -0700 2006&quot;</span><br><span class="line">    RFC822      = &quot;02 Jan 06 15:04 MST&quot;</span><br><span class="line">    RFC822Z     = &quot;02 Jan 06 15:04 -0700&quot; // RFC822 with numeric zone</span><br><span class="line">    RFC850      = &quot;Monday, 02-Jan-06 15:04:05 MST&quot;</span><br><span class="line">    RFC1123     = &quot;Mon, 02 Jan 2006 15:04:05 MST&quot;</span><br><span class="line">    RFC1123Z    = &quot;Mon, 02 Jan 2006 15:04:05 -0700&quot; // RFC1123 with numeric zone</span><br><span class="line">    RFC3339     = &quot;2006-01-02T15:04:05Z07:00&quot;</span><br><span class="line">    RFC3339Nano = &quot;2006-01-02T15:04:05.999999999Z07:00&quot;</span><br><span class="line">    Kitchen     = &quot;3:04PM&quot;</span><br><span class="line">    // Handy time stamps.</span><br><span class="line">    Stamp      = &quot;Jan _2 15:04:05&quot;</span><br><span class="line">    StampMilli = &quot;Jan _2 15:04:05.000&quot;</span><br><span class="line">    StampMicro = &quot;Jan _2 15:04:05.000000&quot;</span><br><span class="line">    StampNano  = &quot;Jan _2 15:04:05.000000000&quot;</span><br><span class="line">)     </span><br></pre></td></tr></table></figure>
<p>注意: galang 中指定的特定时间格式为 “2006-01-02 15:04:05 -0700 MST”， 为了记忆方便，按照美式时间格式 月日时分秒年 外加时区 排列起来依次是 01/02 03:04:05PM ‘06 -0700，刚开始使用时需要注意。</p>
<h3 id="to-time-stamp">to time stamp</h3>
<p>​      func (t Time) Unix() int64<br>
​      func (t Time) UnixNano() int64</p>
<pre><code>  fmt.Println(time.Now().Unix())

  // 获取指定日期的时间戳
  dt, _ := time.Parse(&quot;2016-01-02 15:04:05&quot;, &quot;2018-04-23 12:24:51&quot;)
  fmt.Println(dt.Unix())

  fmt.Println(time.Date(2018, 1,2,15,30,10,0, time.Local).Unix())
</code></pre>
<h3 id="其他">其他</h3>
<p>time 包还提供了一些常用的方法，基本覆盖了大多数业务，从方法名就能知道代表的含义就不一一说明了。</p>
<pre><code>  func (t Time) Date() (year int, month Month, day int)
  func (t Time) Clock() (hour, min, sec int)
  func (t Time) Year() int
  func (t Time) Month() Month
  func (t Time) Day() int
  func (t Time) Hour() int
  func (t Time) Minute() int
  func (t Time) Second() int
  func (t Time) Nanosecond() int
  func (t Time) YearDay() int
  func (t Time) Weekday() Weekday
  func (t Time) ISOWeek() (year, week int)
  func (t Time) IsZero() bool
  func (t Time) Local() Time
  func (t Time) Location() *Location
  func (t Time) Zone() (name string, offset int)
  func (t Time) Unix() int64
</code></pre>
<h1 id="时间类型">时间类型</h1>
<p><code>time.Time</code> 类型表示时间。可以通过 <code>time.Now()</code> 函数获取当前的时间对象，然后获取时间对象的年月日时分秒等信息。</p>
<p>示例代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getTimeNow</span><span class="params">()</span></span> &#123;</span><br><span class="line">	now := time.Now() <span class="comment">//获取当前时间</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;current time:%v\n&quot;</span>, now)</span><br><span class="line"></span><br><span class="line">	year := now.Year()     <span class="comment">//年</span></span><br><span class="line">	month := now.Month()   <span class="comment">//月</span></span><br><span class="line">	day := now.Day()       <span class="comment">//日</span></span><br><span class="line">	hour := now.Hour()     <span class="comment">//小时</span></span><br><span class="line">	minute := now.Minute() <span class="comment">//分钟</span></span><br><span class="line">	second := now.Second() <span class="comment">//秒</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;%d-%02d-%02d %02d:%02d:%02d\n&quot;</span>, year, month, day, hour, minute, second)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="时间戳">时间戳</h1>
<p>时间戳是自 <code>1970年1月1日（08:00:00GMT）</code>至当前时间的总毫秒数。也被称为 <code>Unix时间戳</code>。</p>
<p>示例代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取时间戳</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getUnix</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 获取时间戳</span></span><br><span class="line">	timestamp1 := time.Now().Unix()     <span class="comment">//时间戳</span></span><br><span class="line">	timestamp2 := time.Now().UnixNano() <span class="comment">//纳秒时间戳</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;current timestamp1:%v\n&quot;</span>, timestamp1)</span><br><span class="line">	fmt.Printf(<span class="string">&quot;current timestamp2:%v\n&quot;</span>, timestamp2)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用 <code>time.Unix()</code> 函数可以将时间戳转为时间格式。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">unixConverTime</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 将时间戳转换为时间格式</span></span><br><span class="line">	timestamp := time.Now().Unix() <span class="comment">//时间戳</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;current timestamp1:%v\n&quot;</span>, timestamp)</span><br><span class="line"></span><br><span class="line">	timeObj := time.Unix(timestamp, <span class="number">0</span>) <span class="comment">//将时间戳转为时间格式</span></span><br><span class="line">	fmt.Println(timeObj)</span><br><span class="line">	year := timeObj.Year()     <span class="comment">//年</span></span><br><span class="line">	month := timeObj.Month()   <span class="comment">//月</span></span><br><span class="line">	day := timeObj.Day()       <span class="comment">//日</span></span><br><span class="line">	hour := timeObj.Hour()     <span class="comment">//小时</span></span><br><span class="line">	minute := timeObj.Minute() <span class="comment">//分钟</span></span><br><span class="line">	second := timeObj.Second() <span class="comment">//秒</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;%d-%02d-%02d %02d:%02d:%02d\n&quot;</span>, year, month, day, hour, minute, second)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="时间间隔">时间间隔</h1>
<p><code>time.Duration</code> 是 <code>time</code> 包定义的一个类型，它代表两个时间点之间经过的时间，以纳秒为单位。<code>time.Duration</code> 表示一段时间间隔，可表示的最长时间段大约290年。</p>
<p><code>time</code> 包中定义的时间间隔类型的常量如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> (</span><br><span class="line">    Nanosecond  Duration = <span class="number">1</span></span><br><span class="line">    Microsecond          = <span class="number">1000</span> * Nanosecond</span><br><span class="line">    Millisecond          = <span class="number">1000</span> * Microsecond</span><br><span class="line">    Second               = <span class="number">1000</span> * Millisecond</span><br><span class="line">    Minute               = <span class="number">60</span> * Second</span><br><span class="line">    Hour                 = <span class="number">60</span> * Minute</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>例如：<code>time.Duration</code> 表示1纳秒，<code>time.Second</code> 表示1秒。</p>
<h1 id="时间操作">时间操作</h1>
<h2 id="Add">Add</h2>
<p>求时间+n后的时间：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span></span> Add(d Duration) Time</span><br></pre></td></tr></table></figure>
<p>示例代码如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">timeAdd</span><span class="params">()</span></span> &#123;</span><br><span class="line">	now := time.Now()</span><br><span class="line">	value := now.Add(time.Hour) <span class="comment">// 当前时间加1小时后的时间</span></span><br><span class="line">	fmt.Println(value)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Sub">Sub</h2>
<p>求两个时间之间的差值：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span></span> Sub(u Time) Duration</span><br></pre></td></tr></table></figure>
<p>示例代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">func timeSub() &#123;</span><br><span class="line">	now := time.Now()</span><br><span class="line">	value := now.Sub(now.Add(time.Hour))</span><br><span class="line">	fmt.Println(value)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>返回一个时间段 <code>t-u</code>。如果结果超出了 <code>Duration</code> 可以表示的最大值/最小值，将返回最大值/最小值。要获取时间点 <code>t-d</code>（d为Duration），可以使用 <code>t.Add(-d)</code>。</p>
<h2 id="Equal">Equal</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span></span> Equal(u Time) <span class="type">bool</span></span><br></pre></td></tr></table></figure>
<p>判断两个时间是否相同，会考虑时区的影响，因此不同时区标准的时间也可以正确比较。本方法和用 <code>t==u</code> 不同，这种方法还会比较地点和时区信息。</p>
<h2 id="Before">Before</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span></span> Before(u Time) <span class="type">bool</span></span><br></pre></td></tr></table></figure>
<p>如果t代表的时间点在u之前，返回真；否则返回假。</p>
<h2 id="After">After</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(t Time)</span></span> After(u Time) <span class="type">bool</span></span><br></pre></td></tr></table></figure>
<p>如果t代表的时间点在u之后，返回真；否则返回假。</p>
<p>定时器</p>
<p>使用<code>time.Tick(时间间隔)</code>来设置定时器，定时器的本质上是一个通道（channel）。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">tickDemo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	ticker := time.Tick(time.Second) <span class="comment">//定义一个1秒间隔的定时器</span></span><br><span class="line">	<span class="keyword">for</span> i := <span class="keyword">range</span> ticker &#123;</span><br><span class="line">		fmt.Println(i)<span class="comment">//每秒都会执行的任务</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="时间格式化">时间格式化</h1>
<p>时间类型有一个自带的方法<code>Format</code>进行格式化，需要注意的是Go语言中格式化时间模板不是常见的<code>Y-m-d H:M:S</code>而是使用Go的诞生时间2006年1月2号15点04分（记忆口诀为2006 1 2 3 4）。也许这就是技术人员的浪漫吧。</p>
<p>补充：如果想格式化为12小时方式，需指定<code>PM</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">formatDemo</span><span class="params">()</span></span> &#123;</span><br><span class="line">	now := time.Now()</span><br><span class="line">	<span class="comment">// 格式化的模板为Go的出生时间2006年1月2号15点04分 Mon Jan</span></span><br><span class="line">	<span class="comment">// 24小时制</span></span><br><span class="line">	fmt.Println(now.Format(<span class="string">&quot;2006-01-02 15:04:05.000 Mon Jan&quot;</span>))</span><br><span class="line">	<span class="comment">// 12小时制</span></span><br><span class="line">	fmt.Println(now.Format(<span class="string">&quot;2006-01-02 03:04:05.000 PM Mon Jan&quot;</span>))</span><br><span class="line">	fmt.Println(now.Format(<span class="string">&quot;2006/01/02 15:04&quot;</span>))</span><br><span class="line">	fmt.Println(now.Format(<span class="string">&quot;15:04 2006/01/02&quot;</span>))</span><br><span class="line">	fmt.Println(now.Format(<span class="string">&quot;2006/01/02&quot;</span>))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="解析字符串格式的时间">解析字符串格式的时间</h1>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">now := time.Now()</span><br><span class="line">fmt.Println(now)</span><br><span class="line"><span class="comment">// 加载时区</span></span><br><span class="line">loc, err := time.LoadLocation(<span class="string">&quot;Asia/Shanghai&quot;</span>)</span><br><span class="line"><span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">	fmt.Println(err)</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 按照指定时区和指定格式解析字符串时间</span></span><br><span class="line">timeObj, err := time.ParseInLocation(<span class="string">&quot;2006/01/02 15:04:05&quot;</span>, <span class="string">&quot;2019/08/04 14:15:20&quot;</span>, loc)</span><br><span class="line"><span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">	fmt.Println(err)</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br><span class="line">fmt.Println(timeObj)</span><br><span class="line">fmt.Println(timeObj.Sub(now))</span><br></pre></td></tr></table></figure>
<p>练习题：</p>

</div>


  <div class="book-comments">
    




  </div>



<script src="/js/book-post.js"></script>

        </div>
      </div>
      <div class="column col-2 hide-lg">
        <div class="book-post-info">
  
    <div class="book-post-meta">

  <div class="author">

    <!-- Author image -->
    <div class="author-img">
      
        <figure
          class="avatar avatar-lg"
          data-initial="W"
          style="background-color: #3b4351;">
        </figure>
      
    </div>

    <!-- Author title -->
    <div class="author-title">
      <div>WangPengLiang</div>
      <div>2022-03-30</div>
    </div>
  </div>

  

  <div class="divider"></div>
</div>
  

  <div class="book-tocbot">
</div>
<div class="book-tocbot-menu">
  <a class="book-toc-expand" onclick="expand_toc()">Expand all</a>
  <a onclick="go_top()">Back to top</a>
  <a onclick="go_bottom()">Go to bottom</a>
</div>


<script src="/js/book-toc.js"></script>

</div>
      </div>
    </div>
  </div>
  
  <a class="off-canvas-overlay" onclick="hide_canvas()"></a>
</div>

</body>
</html>


<script src="/js/book.js"></script>
